package com.hitqz.robot.biz.schedule;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hitqz.robot.api.business.entity.PatrolResultEntity;
import com.hitqz.robot.api.business.entity.RobotWarningRecordEntity;
import com.hitqz.robot.api.business.entity.TicketsEntity;
import com.hitqz.robot.api.business.entity.TicketsTaskEntity;
import com.hitqz.robot.biz.config.PatrolProperties;
import com.hitqz.robot.biz.service.PatrolResultService;
import com.hitqz.robot.biz.service.RobotWarningRecordService;
import com.hitqz.robot.biz.service.TicketsService;
import com.hitqz.robot.biz.service.TicketsTaskService;
import com.hitqz.robot.common.file.core.FileProperties;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;

@Component
@Slf4j
@AllArgsConstructor
public class DeleteSchedule {

    private final ExecutorService customThreadPool;

    private final FileProperties fileProperties;

    private final PatrolProperties patrolProperties;

    private final RobotWarningRecordService robotWarningRecordService;

    private final TicketsService ticketsService;

    private final TicketsTaskService ticketsTaskService;

    private final PatrolResultService patrolResultService;



    @Scheduled(cron = "0 0 * * * ?")
    private void deleteWarning(){
        CompletableFuture.runAsync(()->{
            List<RobotWarningRecordEntity> list = robotWarningRecordService.list(Wrappers.<RobotWarningRecordEntity>lambdaQuery().le(RobotWarningRecordEntity::getTime, DateUtil.offset(DateUtil.date(), DateField.DAY_OF_YEAR, -patrolProperties.getMaxHistory())));
            if (!list.isEmpty()){
                robotWarningRecordService.removeBatchByIds(list);
                log.info("定期删除告警记录");
            }
        },customThreadPool);
    }

    @Scheduled(cron = "0 0 * * * ?")
    private void deleteTicketsAndPatrolResult(){
        CompletableFuture.runAsync(()->{
            try {
                String basePath = fileProperties.getLocal().getBasePath();
                File patrolDir = new File(basePath + File.separator + "patrol");
                File warningDir = new File(basePath + File.separator + "warning");
                File excelDir = new File(basePath + File.separator + "excel");
                // 查看文件大小
                long fileSize = 0L;
                if (FileUtil.exist(patrolDir)) {
                    fileSize += FileUtil.size(patrolDir);
                }
                if (FileUtil.exist(warningDir)) {
                    fileSize += FileUtil.size(warningDir);
                }
                if (FileUtil.exist(excelDir)) {
                    fileSize += FileUtil.size(excelDir);
                }
                log.info("当前文件大小为:{} G,限制保存文件大小:{} G", fileSize / 1024 / 1024 / 1024, patrolProperties.getMaxSize());
                if ((fileSize / 1024 / 1024 / 1024) > patrolProperties.getMaxSize()) {
                    log.info("文件大小超过限制,开始删除");
                    DateTime offset = DateUtil.offset(DateUtil.date(), DateField.DAY_OF_YEAR, -patrolProperties.getMaxHistory());
                    List<TicketsEntity> list = ticketsService.list(Wrappers.<TicketsEntity>lambdaQuery().le(TicketsEntity::getCreateTime, offset));
                    if (!list.isEmpty()) {
                        List<Long> idList = list.stream().map(TicketsEntity::getId).toList();
                        ticketsTaskService.remove(Wrappers.<TicketsTaskEntity>lambdaQuery().in(TicketsTaskEntity::getTicketsId, idList));
                        patrolResultService.remove(Wrappers.<PatrolResultEntity>lambdaQuery().in(PatrolResultEntity::getTicketsId, idList));
                        ticketsService.removeBatchByIds(list);
                        //删除巡检文件
                        deleteOldFiles(patrolDir, offset.getTime());
                        //删除告警图片
                        deleteOldFiles(warningDir, offset.getTime());
                        //删除excel文件
                        deleteOldFiles(excelDir, offset.getTime());
                        log.info("定期删除文件成功");
                    }
                }
                log.info("定期检测结果和文件");
            }catch (Exception e){
                log.error("定期删除文件异常", e);
            }
        },customThreadPool);
    }


    public static void deleteOldFiles(File folder, long cutoffTime) {
        File[] files = folder.listFiles();
        if (files == null) return;
        for (File file : files) {
            if (file.isDirectory()) {
                deleteOldFiles(file, cutoffTime); // 递归处理子文件夹
                if (FileUtil.isDirEmpty(file)) { // 删除空文件夹
                    FileUtil.del(file);
                }
            } else {
                if (file.lastModified() < cutoffTime) { // 判断文件修改时间
                    FileUtil.del(file);
                }
            }
        }
    }




}
